package com.acme.service.bank.impl;

import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.domain.bank.Gender;
import com.acme.exceptions.ClientExistsException;
import com.acme.service.bank.BankService;

import java.io.*;

public class BankServiceImpl implements BankService {
    @Override
    public void saveBank(final Bank bank, final String pathTo) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(pathTo)) {
            try (BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
                    oos.writeObject(bank);
                }
            }
        }
    }

    @Override
    public Bank loadBank(final String pathFrom) throws IOException, ClassNotFoundException {
        try (FileInputStream fis = new FileInputStream(pathFrom)) {
            try (BufferedInputStream bis = new BufferedInputStream(fis)) {
                try (ObjectInputStream ois = new ObjectInputStream(bis)) {
                    return (Bank) ois.readObject();
                }
            }
        }
    }

    @Override
    public Client addClient(Bank bank, String name, Gender gender) throws ClientExistsException {
        Client client = new Client(name, gender);
        bank.addClient(client);
        return client;
    }
}